<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Request;

/**
 * 积分专区
 */
class Integral extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function get_integralList()
    {
        $request = [
            'page' => $this->request->param('page') ?: 1,
            'name' => $this->request->param('name'),
            'bigNum' => $this->request->param('bigNum'),
            'smallNum' => $this->request->param('smallNum'),
            'is_speciality' => $this->request->param('is_speciality'),
        ];
        $page = $request['page'];
        $name = $request['name'];
        $bigNum = $request['bigNum'];
        $smallNum = $request['smallNum'];
        $is_speciality = $request['is_speciality'];
        $sql = Db::name("goods_integral")
            ->where("status = 1");
        if (isset($name)) {
            $sql->where("name like '%" . $name . "%'");
        }
        if (isset($bigNum)) {
            $sql->where("use_integral <= $bigNum");
        }
        if (isset($smallNum)) {
            $sql->where("use_integral >= $smallNum");
        }
        if (isset($is_speciality)) {
            $sql->where("is_speciality = $is_speciality");
        }
        $list = $sql->order('createtime', 'desc')
            ->order('sale_num', 'asc')
            ->field("id,name,image,price,old_price,sale_num,use_integral")
            ->paginate(10);
        $goods = $list->items();
//        $id = array();
//        foreach ($goods as $v) {
//            $id[] = $v['id'];
//        }
//        shuffle($id);
//        $goods = array();
//        $goods2 = Db::name("goods_integral");
//        if ($id) {
//            $id = array_slice($id, ($page - 1) * 10, 10);
//            foreach ($id as $v) {
//                $goods[] = $goods2
//                    ->where("id = {$v}")
//                    ->field("id,name,image,price,old_price,sale_num,use_integral")
//                    ->find();
//            }
//        }
        foreach ($goods as $k => $v) {
            $goods[$k]['goods_image'] = path($v['image']);
            preg_match_all("/./us", $v['name'], $match);
            $goods[$k]['length'] = count($match[0]);
            if ($goods[$k]['length'] > 10) {
                $goods[$k]['height'] = 536;
            } else {
                $goods[$k]['height'] = 500;
            }
        }
        $this->success('成功', $goods, 200);
    }

    public function exchange_integral()
    {
        $this->error('功能维护中,暂时无法使用', '', 239);
        $request = Request::instance();
        $goods_integral_id = $request->param("goods_integral_id");
        $goods_spec_one_id = $request->param("goods_spec_one_id");
        $goods_spec_two_id = $request->param("goods_spec_two_id") ?: 0;
        $goods_num = $request->param("goods_num") ? $request->param("goods_num") : 1;
        $uid = $request->param("uid");
        $token = $request->param("token") ?: 0;//
        $jm_str = $request->param("jm_str") ?: 0;//
        $res = yanzheng($uid, $token, $jm_str);
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        if (empty($uid)) {
            $this->error("请登录", '', '201');
        }

        try {
            Db::startTrans();
            if (!$goods_integral_id || !$goods_spec_one_id) {
                $this->error('请给予商品id', '', 206);
            }
            $goods_integral = Db::name("goods_integral")->where(['id' => $goods_integral_id])->find();
            if ($goods_integral['status'] != 1) {
                $this->error('商品已被下架无法购买', '', 207);
            }
            $shuilv = $goods_integral['shuilv'];
            if ((isset($goods_spec_one_id) && !empty($goods_spec_one_id) && $goods_spec_one_id)) {
                $goods_stock = Db::name("goods_stock")->where(['goods_integral_id' => $goods_integral_id, 'goods_spec_one_id' => $goods_spec_one_id, 'goods_spec_two_id' => $goods_spec_two_id])->find();
                $goods_spec_one_name = "";
                $goods_spec_two_name = "";
                $goods_spec_one_name = Db::name("goods_spec_one")->where(['id' => $goods_stock['goods_spec_one_id']])->find();
                $goods_spec_two_name = Db::name("goods_spec_two")->where(['id' => $goods_stock['goods_spec_two_id']])->find();
                if ($goods_spec_one_name) {
                    $goods_spec_one_name = $goods_spec_one_name['name'];
                }
                if ($goods_spec_two_name) {
                    $goods_spec_two_name = $goods_spec_two_name['name'];
                }
                if (!$goods_stock) {
                    $this->error('商品已被下架无法购买', '', 207);
                }
                $num = $goods_stock['num'];
                if ($goods_num > $num) {
                    //$this->error('商品库存不足无法购买', '', 208);
                }
                $allprice = $goods_stock['price'] * $goods_num;
                $supplier_cost = $goods_stock['cost_price'] * $goods_num;
                $one_use_integral = $goods_stock['use_integral'];
                $goods_spec_one_id = $goods_stock['goods_spec_one_id'];
                $goods_spec_two_id = $goods_stock['goods_spec_two_id'];
                $goods_cost_price = $goods_stock['cost_price'];
                $goods_price = $goods_stock['price'];
                if ($goods_spec_two_name) {
                    $goods_spec_name = $goods_spec_one_name . "($goods_spec_two_name)";
                } else {
                    $goods_spec_name = $goods_spec_one_name;
                }
            } else {
                $this->error('请给予商品规格id', '', 206);
            }
            $image = $goods_integral['image'];
            $goods_name = $goods_integral['name'];
            $use_integral = $one_use_integral * $goods_num;
            $user = Db::name("userhome")->where(['id' => $uid])->lock(true)->find();
            if (intval(strval($user['use_integral'] * 100)) < intval(strval($use_integral * 100))) {
                $this->error('可使用积分不足,无法购买', '', 209);
            }
            $order = [
                'supplier_id' => $goods_integral['supplier_id'],
                'userhome_id' => $uid,
                'createtime' => time(),//下单时间
                //生成支付单号
                'paycode' => date('Ymd') . '1' . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . rand(0, 9),//生成支付单号
                //生成订单号
                'ordernum' => date('Ymd') . '2' . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 6, 12), 1))), 0, 8) . rand(0, 9),//生成订单号
                'orderpaytype' => 1,
                'allprice' => $allprice,
                'supplier_cost' => $supplier_cost,
                'status' => 2,
                'paytype' => 4,
                'is_yc' => 0,
                'phone' => $request->param("phone"),//用户手机号
                'name' => $request->param("name"),//用户名称
                'address' => $request->param("address"),//用户地址
                'paytime' => time(),
                'is_integral' => 1,
                'use_integral' => $use_integral
            ];
            $order_id = DB::name('order')->insertGetId($order);
            $orderDetail = [
                'order_id' => $order_id,
                'userhome_id' => $uid,
                'goods_id' => $goods_integral_id,
                'goods_spec_one_id' => $goods_spec_one_id,
                'goods_spec_two_id' => $goods_spec_two_id,
                'image' => $image,
                'cost_price' => $goods_cost_price,
                'price' => $goods_price,
                'name' => $goods_name,
                'shuilv' => $shuilv,
                'goods_spec_name' => $goods_spec_name,
                'num' => $goods_num,
                'integral' => $one_use_integral,
            ];
            $order_detail_id = DB::name('orderdetail')->insertGetId($orderDetail);
            DB::name('userhome')->where(['id' => $uid])->setDec("use_integral", $use_integral);
            $incomeScoreLog = [
                'userId' => $uid,
                'score' => $use_integral,
                'grandScore' => $user['add_integral'],
                'consumeScore' => (intval(strval($user['use_integral'] * 100)) - intval(strval($use_integral * 100))) / 100,
                'source' => "CONSUME",
                'order_id' => $order_id,
                'order_detail_id' => $order_detail_id,
                'createTime' => date("Y-m-d H:i:s"),//下单时间
                'status' => "ENTER",
                'break' => "使用了积分兑换了积分商品"
            ];
            DB::name('user_income_score_log')->insertGetId($incomeScoreLog);
            Db::name("goods_stock")->where(['id' => $goods_stock['id']])->setDec("num", $goods_num);
            Db::name("goods_integral")->where(['id' => $goods_stock['goods_integral_id']])->setInc("sale_num", $goods_num);
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success();
    }

    public function get_integralShow()
    {
        $request = [
            'goods_integral_id' => $this->request->param('goods_integral_id'),//商品id
            'uid' => $this->request->param('uid'),//
        ];
        /* 验证不能为空的字段*/
        $EmptyData = array('goods_integral_id');
        foreach ($EmptyData as $oeVo) {
            $retInfo = EmptyValidate($oeVo, $request);
            if ($retInfo) {
                $this->error($retInfo, '', 201);
            }
        }
        $uid = $request['uid'];
        if ($uid) {
            //$res = yanzheng($uid, $this->request->param("token"), $this->request->param("jm_str"));
            // if ($res == 0) {
            //     $this->error('账号异常','',206);
            // }
            // if ($res == 1) {
            //     $this->error('非法的请求','',201);
            // }
        }

        $goods_integral_id = $request['goods_integral_id'];
        $goods_integral = Db::name("goods_integral")
            ->where("id = {$goods_integral_id}")
            ->find();
        $goods_integral['content'] = content_url($goods_integral['content']);
        $goods_integral['image'] = path($goods_integral['image']);
        $images = explode(',', $goods_integral['images']);
        $image = array();
        foreach ($images as $kk => $vv) {
            $image[] = path($vv);
        }
        $goods_integral['images'] = $image;

        //属性

        $kucun = DB::name('goods_stock t1')
            ->join('goods_spec_one t2', 't1.goods_spec_one_id = t2.id')
            ->leftJoin('goods_spec_two t3', 't1.goods_spec_two_id = t3.id')
            ->where("t1.goods_integral_id = {$goods_integral_id}")
            ->field('t1.*,t2.name as goods_spec_one_name,t3.name as goods_spec_two_name')
            ->select();
        $goods_spec_one_id = array();
        $goods_spec_two_id = array();
        foreach ($kucun as $k => $v) {
            $goods_spec_one_id[] = $v['goods_spec_one_id'];
            $goods_spec_two_id[] = $v['goods_spec_two_id'];
        }
        $goods_spec_one_id = implode(',', $goods_spec_one_id);
        $goods_spec_two_id = implode(',', $goods_spec_two_id);
        $goods_spec_one = array();
        if ($goods_spec_one_id) {
            $goods_spec_one = Db::name("goods_spec_one")->where("id in ($goods_spec_one_id)")->field("id,name")->select();
            if ($goods_integral['spec2'] == '') {
                $goods_stock = DB::name('goods_stock');
                foreach ($goods_spec_one as $key => $value) {
                    $goods_spec_one[$key]['num'] = $goods_stock->where('goods_spec_one_id', $value['id'])->value('num');
                }
            }
        }
        $goods_spec_two = array();
        if ($goods_spec_two_id) {
            $goods_spec_two = Db::name("goods_spec_two")->where("id in ($goods_spec_two_id)")->field("id,name")->select();
        }
        $data = array();
        $data['goods'] = $goods_integral;
        $data['goods_spec_one'] = $goods_spec_one;
        $data['goods_spec_two'] = $goods_spec_two;
        $data['goods_stock'] = $kucun;
        $this->success('成功', $data, 200);
    }

    public function exchangeLog()
    {
        $request = Request::instance();
        $page = $request->param("page") ?: 1;
        $uid = $request->param("uid");
        $token = $request->param("token") ?: 0;//
        $jm_str = $request->param("jm_str") ?: 0;//
        $res = yanzheng($uid, $token, $jm_str);
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        if (empty($uid)) {
            $this->error("请登录", '', '201');
        }

        $list = Db::name("user_income_score_log t1")
            ->join('order t2', 't1.order_id=t2.id', 'LEFT')
            ->join('orderdetail t3', 't1.order_detail_id=t3.id', 'LEFT')
            ->join('red t4', 't1.red_id=t4.id', 'LEFT')
            ->whereIn("t1.source", ['CONSUME'])
            ->where("t1.userId", $uid)
            ->order('t1.createtime', 'desc')
            ->field("t1.userId,t1.incomeScoreLogId,t1.score,t1.source,t1.order_id,t1.order_detail_id,t3.image,t3.name as goods_name,t3.goods_spec_name,t3.num,t2.ordernum,t2.status as order_status,t1.redNo,
            t1.red_id,t4.redName,t4.redImage,t1.redNum,t1.redType,t1.createTime,t1.status,t2.phone,t2.name,t2.address")
            ->paginate(10);
        $goods = $list->items();
        foreach ($goods as $k => $v) {
            $goods[$k]['goods_image'] = path($v['image']);
            preg_match_all("/./us", $v['goods_name'], $match);
            $goods[$k]['length'] = count($match[0]);
            if ($goods[$k]['length'] > 10) {
                $goods[$k]['height'] = 536;
            } else {
                $goods[$k]['height'] = 500;
            }
        }
        $this->success('成功', $goods, 200);
    }

    public function lunck()
    {
        $lunck = Db::name("activity_luck")->find();
        $lunckList = Db::name("activity_luck_detail")->select();
        foreach ($lunckList as $k => $v) {
            $lunckList[$k]['lunck_image'] = path($v['lunck_image']);
        }
        $request = Request::instance();
        $uid = $request->param("uid");
        $user = Db::name("userhome")->where('id', $uid)->find();
        $lunck['is_luck'] = $user['is_luck'];
        $lunck['lunckList'] = $lunckList;
        $lunck['totalNum'] = count($lunckList);
        $this->success('成功', $lunck, 200);
    }

    public function lunckGo()
    {
        $request = Request::instance();
        $uid = $request->param("uid");
        $token = $request->param("token") ?: 0;//
        $jm_str = $request->param("jm_str") ?: 0;//
        $res = yanzheng($uid, $token, $jm_str);
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        if (empty($uid)) {
            $this->error("请登录", '', '201');
        }
        $lunck = Db::name("activity_luck")->find();
        if (empty($lunck)) {
            $this->error("大转盘维护中,暂时无法使用");
        }
        if (!$lunck['status']) {
            $this->error("大转盘维护中,暂时无法使用");
        }
        $publicIntegral = $lunck['publicIntegral'] ?: 0;
        $lunckList = Db::name("activity_luck_detail")->orderRaw('rand()')->select();
        $award = [];
        try {
            Db::startTrans();
            $user = Db::name("userhome")->where('id', $uid)->lock()->find();
            if ($user) {
                if ($user['is_luck'] == 1) {
                    if (intval(strval($user['use_integral'] * 100)) < intval(strval($lunck['integral'] * 100))) {
                        $this->error('可使用积分不足,无法使用');
                    }
                }
                //$award = $lunckList[rand(0, 7)];
                foreach ($lunckList as $key => $value) {
                    $num = rand(1, 1000000);
                    if ($value['rate'] == 0) {
                        $award = $value;
                        break;
                    }
                    if ($num <= $value['rate']) {
                        if ((intval(strval($value['lunck_cost'] * 100)) + intval(strval($user['luck_add_integral'] * 100))) <= intval(strval(($user['luck_integral'] + $publicIntegral) * 100))) {
                            $award = $value;
                            break;
                        }
                    }
                }
                if (!isset($award['lunck_type'])) {
                    $this->error("大转盘维护中,暂时无法使用");
                }
                //先判断是否每日第一抽
                $incomeScoreLog = [];
                $time = date("Y-m-d H:i:s");
                $isDay = 0;
                $is_exchange = 0;
                if ($user['is_luck'] == 1) {
                    //不是第一抽，开始加入积分消费
                    $incomeScoreLog[0]['userId'] = $uid;
                    $incomeScoreLog[0]['score'] = $lunck['integral'];
                    $incomeScoreLog[0]['grandScore'] = $user['add_integral'];
                    $incomeScoreLog[0]['consumeScore'] = $user['use_integral'] - $lunck['integral'];
                    $incomeScoreLog[0]['source'] = "GAMBLE";
                    $incomeScoreLog[0]['createTime'] = $time;
                    $incomeScoreLog[0]['break'] = "大转盘";
                    $incomeScoreLog[0]['status'] = "ENTER";
                    $user['use_integral'] = $incomeScoreLog[0]['consumeScore'];
                    $user['luck_integral'] += $lunck['integral'];
                } else {
                    $user['luck_integral'] += $lunck['integral'] / 10;
                    $isDay = 1;
                }
                $incomeScoreLogNum = count($incomeScoreLog);
                if ($award['lunck_type'] == 1) {
                    $incomeScoreLog[$incomeScoreLogNum]['userId'] = $uid;
                    $incomeScoreLog[$incomeScoreLogNum]['score'] = $award['lunck_cost'];
                    $incomeScoreLog[$incomeScoreLogNum]['grandScore'] = $user['add_integral'] + $award['lunck_cost'];
                    $incomeScoreLog[$incomeScoreLogNum]['consumeScore'] = $user['use_integral'] + $award['lunck_cost'];
                    $incomeScoreLog[$incomeScoreLogNum]['source'] = "GAMBLEGET";
                    $incomeScoreLog[$incomeScoreLogNum]['createTime'] = $time;
                    $incomeScoreLog[$incomeScoreLogNum]['break'] = "大转盘获取";
                    $incomeScoreLog[$incomeScoreLogNum]['status'] = "ENTER";
                    $user['add_integral'] = $incomeScoreLog[$incomeScoreLogNum]['grandScore'];
                    $user['use_integral'] = $incomeScoreLog[$incomeScoreLogNum]['consumeScore'];
                    $user['luck_add_integral'] += $award['lunck_cost'];
                    $is_exchange = 1;
                } else if ($award['lunck_type'] == 2) {
                    $user['luck_add_integral'] += $award['lunck_cost'];
                } else {
                    $is_exchange = 1;
                }
                $activity_luck_detail_log = [];
                $activity_luck_detail_log['userId'] = $uid;
                $activity_luck_detail_log['lunck_name'] = $award['lunck_name'];
                $activity_luck_detail_log['lunck_image'] = $award['lunck_image'];
                $activity_luck_detail_log['lunck_type'] = $award['lunck_type'];
                $activity_luck_detail_log['lunck_cost'] = $award['lunck_cost'];
                $activity_luck_detail_log['integral'] = $award['lunck_cost'];
                $activity_luck_detail_log['createTime'] = $time;
                $activity_luck_detail_log['isDay'] = $isDay;
                $activity_luck_detail_log['is_exchange'] = $is_exchange;
                Db::name("activity_luck_detail_log")->insert($activity_luck_detail_log);
                Db::name("user_income_score_log")->insertAll($incomeScoreLog);
                Db::name("userhome")->where('id', $uid)->update([
                    'add_integral' => $user['add_integral'],
                    'use_integral' => $user['use_integral'],
                    'luck_integral' => $user['luck_integral'],
                    'luck_add_integral' => $user['luck_add_integral'],
                    'is_luck' => 1
                ]);
                if ($award['lunck_type'] == 1) {
                    $orderService = new Order();
                    $levelList = Db::name("level")->select();
                    $orderService->upLevel($levelList, $user);
                }
            }
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功', $award, 200);
    }

    public function lunckLog()
    {
        $request = Request::instance();
        $uid = $request->param("uid");
        $token = $request->param("token") ?: 0;//
        $jm_str = $request->param("jm_str") ?: 0;//
        $pagesize = $request->param("pagesize") ?: 0;//
        $res = yanzheng($uid, $token, $jm_str);
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        if (empty($uid)) {
            $this->error("请登录", '', '201');
        }
        $user_income_score_log = Db::name("activity_luck_detail_log")->where('userId', $uid)->order('createTime', 'desc')->paginate($pagesize);

        $data = [];
        $data['lunckList'] = $user_income_score_log->items();
        $data['totalNum'] = $user_income_score_log->total();
        $this->success('成功', $data, 200);
    }

    public function getLuckLog()
    {
        $request = Request::instance();
        $pagesize = $request->param("pagesize") ?: 20;//
        $luckLog = Db::name("activity_luck_detail_log_fake")->orderRaw('rand()')->limit($pagesize)->select();
        $this->success('成功', $luckLog, 200);
    }

    public function lunckFake()
    {
        $lunckList = Db::name("activity_luck_detail")->where('lunck_type != 0')->order('sort', 'asc')->select();
        $num = count($lunckList) - 1;
        $luckLog = [];
        $phone = [133, 153, 180, 181, 189, 177, 149, 130, 131, 132, 155, 156, 145, 185, 186, 176, 175, 135, 136, 137, 138, 139, 150, 151, 152, 157, 158, 159, 182, 183, 184, 187, 188, 147, 178];
        for ($i = 0; $i < 2000; $i++) {
            $award = $lunckList[rand(0, $num)];
            $luckLog[$i]['id'] = $i + 1;
            $typeNum = rand(1, 4);
            if ($typeNum == 1) {
                $name = $this->createNickname();
                $strLen = strlen($name);
                if ($strLen > 6) {
                    $str = null;
                    for ($j = 0; $j < ($strLen / 3 - 2); $j++) {
                        $str .= "*";
                    }
                    $name = substr_replace($name, $str, 3, $strLen - 6);
                }
                $luckLog[$i]['name'] = $name;
            } else if ($typeNum == 2) {
                $name = $phone[rand(0, count($phone) - 1)] . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9);
                $name = substr_replace($name, "****", 3, 4);
                $luckLog[$i]['name'] = $name;
            } else if ($typeNum == 3) {
                $name = $this->getname();
                $strLen = strlen($name);
                if ($strLen > 6) {
                    $str = null;
                    for ($j = 0; $j < ($strLen / 3 - 2); $j++) {
                        $str .= "*";
                    }
                    $name = substr_replace($name, $str, 3, $strLen - 6);
                } else {
                    $name = substr_replace($name, "*", 0, 3);
                }
                $luckLog[$i]['name'] = $name;
            } else {
                $name = $this->randomkeys(rand(4, 12));
                $strLen = strlen($name);
                if ($strLen > 2) {
                    $str = null;
                    for ($j = 0; $j < $strLen - 2; $j++) {
                        $str .= "*";
                    }
                    $name = substr_replace($name, $str, 1, $strLen - 2);
                }
                $luckLog[$i]['name'] = $name;
            }
            $luckLog[$i]['lunck_name'] = $award['lunck_name'];
        }
        Db::name("activity_luck_detail_log_fake")->where('id != 0')->delete();
        Db::name("activity_luck_detail_log_fake")->insertAll($luckLog);
        $this->success('成功', true, 200);
    }

    function randomkeys($length)
    {
        $returnStr = '';
        $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
        for ($i = 0; $i < $length; $i++) {
            $returnStr .= $pattern [mt_rand(0, 61)]; //生成php随机数
        }
        return $returnStr;
    }

    function createNickname()
    {
        $randomXing = array('快乐的', '冷静的', '醉熏的', '潇洒的', '糊涂的', '积极的', '冷酷的', '深情的', '粗暴的', '温柔的', '可爱的', '愉快的', '义气的', '认真的', '威武的', '帅气的', '传统的', '潇洒的', '漂亮的', '自然的', '专一的', '听话的', '昏睡的', '狂野的', '等待的', '搞怪的', '幽默的', '魁梧的', '活泼的', '开心的', '高兴的', '超帅的', '留胡子的', '坦率的', '直率的', '轻松的', '痴情的', '完美的', '精明的', '无聊的', '有魅力的', '丰富的', '繁荣的', '饱满的', '炙热的', '暴躁的', '碧蓝的', '俊逸的', '英勇的', '健忘的', '故意的', '无心的', '土豪的', '朴实的', '兴奋的', '幸福的', '淡定的', '不安的', '阔达的', '孤独的', '独特的', '疯狂的', '时尚的', '落后的', '风趣的', '忧伤的', '大胆的', '爱笑的', '矮小的', '健康的', '合适的', '玩命的', '沉默的', '斯文的', '香蕉', '苹果', '鲤鱼', '鳗鱼', '任性的', '细心的', '粗心的', '大意的', '甜甜的', '酷酷的', '健壮的', '英俊的', '霸气的', '阳光的', '默默的', '大力的', '孝顺的', '忧虑的', '着急的', '紧张的', '善良的', '凶狠的', '害怕的', '重要的', '危机的', '欢喜的', '欣慰的', '满意的', '跳跃的', '诚心的', '称心的', '如意的', '怡然的', '娇气的', '无奈的', '无语的', '激动的', '愤怒的', '美好的', '感动的', '激情的', '激昂的', '震动的', '虚拟的', '超级的', '寒冷的', '精明的', '明理的', '犹豫的', '忧郁的', '寂寞的', '奋斗的', '勤奋的', '现代的', '过时的', '稳重的', '热情的', '含蓄的', '开放的', '无辜的', '多情的', '纯真的', '拉长的', '热心的', '从容的', '体贴的', '风中的', '曾经的', '追寻的', '儒雅的', '优雅的', '开朗的', '外向的', '内向的', '清爽的', '文艺的', '长情的', '平常的', '单身的', '伶俐的', '高大的', '懦弱的', '柔弱的', '爱笑的', '乐观的', '耍酷的', '酷炫的', '神勇的', '年轻的', '唠叨的', '瘦瘦的', '无情的', '包容的', '顺心的', '畅快的', '舒适的', '靓丽的', '负责的', '背后的', '简单的', '谦让的', '彩色的', '缥缈的', '欢呼的', '生动的', '复杂的', '慈祥的', '仁爱的', '魔幻的', '虚幻的', '淡然的', '受伤的', '雪白的', '高高的', '糟糕的', '顺利的', '闪闪的', '羞涩的', '缓慢的', '迅速的', '优秀的', '聪明的', '含糊的', '俏皮的', '淡淡的', '坚强的', '平淡的', '欣喜的', '能干的', '灵巧的', '友好的', '机智的', '机灵的', '正直的', '谨慎的', '俭朴的', '殷勤的', '虚心的', '辛勤的', '自觉的', '无私的', '无限的', '踏实的', '老实的', '现实的', '可靠的', '务实的', '拼搏的', '个性的', '粗犷的', '活力的', '成就的', '勤劳的', '单纯的', '落寞的', '朴素的', '悲凉的', '忧心的', '洁净的', '清秀的', '自由的', '小巧的', '单薄的', '贪玩的', '刻苦的', '干净的', '壮观的', '和谐的', '文静的', '调皮的', '害羞的', '安详的', '自信的', '端庄的', '坚定的', '美满的', '舒心的', '温暖的', '专注的', '勤恳的', '美丽的', '腼腆的', '优美的', '甜美的', '甜蜜的', '整齐的', '动人的', '典雅的', '尊敬的', '舒服的', '妩媚的', '秀丽的', '喜悦的', '甜美的', '彪壮的', '强健的', '大方的', '俊秀的', '聪慧的', '迷人的', '陶醉的', '悦耳的', '动听的', '明亮的', '结实的', '魁梧的', '标致的', '清脆的', '敏感的', '光亮的', '大气的', '老迟到的', '知性的', '冷傲的', '呆萌的', '野性的', '隐形的', '笑点低的', '微笑的', '笨笨的', '难过的', '沉静的', '火星上的', '失眠的', '安静的', '纯情的', '要减肥的', '迷路的', '烂漫的', '哭泣的', '贤惠的', '苗条的', '温婉的', '发嗲的', '会撒娇的', '贪玩的', '执着的', '眯眯眼的', '花痴的', '想人陪的', '眼睛大的', '高贵的', '傲娇的', '心灵美的', '爱撒娇的', '细腻的', '天真的', '怕黑的', '感性的', '飘逸的', '怕孤独的', '忐忑的', '高挑的', '傻傻的', '冷艳的', '爱听歌的', '还单身的', '怕孤单的', '懵懂的');

        $randomMing = array('嚓茶', '凉面', '便当', '毛豆', '花生', '可乐', '灯泡', '哈密瓜', '野狼', '背包', '眼神', '缘分', '雪碧', '人生', '牛排', '蚂蚁', '飞鸟', '灰狼', '斑马', '汉堡', '悟空', '巨人', '绿茶', '自行车', '保温杯', '大碗', '墨镜', '魔镜', '煎饼', '月饼', '月亮', '星星', '芝麻', '啤酒', '玫瑰', '大叔', '小伙', '哈密瓜，数据线', '太阳', '树叶', '芹菜', '黄蜂', '蜜粉', '蜜蜂', '信封', '西装', '外套', '裙子', '大象', '猫咪', '母鸡', '路灯', '蓝天', '白云', '星月', '彩虹', '微笑', '摩托', '板栗', '高山', '大地', '大树', '电灯胆', '砖头', '楼房', '水池', '鸡翅', '蜻蜓', '红牛', '咖啡', '机器猫', '枕头', '大船', '诺言', '钢笔', '刺猬', '天空', '飞机', '大炮', '冬天', '洋葱', '春天', '夏天', '秋天', '冬日', '航空', '毛衣', '豌豆', '黑米', '玉米', '眼睛', '老鼠', '白羊', '帅哥', '美女', '季节', '鲜花', '服饰', '裙子', '白开水', '秀发', '大山', '火车', '汽车', '歌曲', '舞蹈', '老师', '导师', '方盒', '大米', '麦片', '水杯', '水壶', '手套', '鞋子', '自行车', '鼠标', '手机', '电脑', '书本', '奇迹', '身影', '香烟', '夕阳', '台灯', '宝贝', '未来', '皮带', '钥匙', '心锁', '故事', '花瓣', '滑板', '画笔', '画板', '学姐', '店员', '电源', '饼干', '宝马', '过客', '大白', '时光', '石头', '钻石', '河马', '犀牛', '西牛', '绿草', '抽屉', '柜子', '往事', '寒风', '路人', '橘子', '耳机', '鸵鸟', '朋友', '苗条', '铅笔', '钢笔', '硬币', '热狗', '大侠', '御姐', '萝莉', '毛巾', '期待', '盼望', '白昼', '黑夜', '大门', '黑裤', '钢铁侠', '哑铃', '板凳', '枫叶', '荷花', '乌龟', '仙人掌', '衬衫', '大神', '草丛', '早晨', '心情', '茉莉', '流沙', '蜗牛', '战斗机', '冥王星', '猎豹', '棒球', '篮球', '乐曲', '电话', '网络', '世界', '中心', '鱼', '鸡', '狗', '老虎', '鸭子', '雨', '羽毛', '翅膀', '外套', '火', '丝袜', '书包', '钢笔', '冷风', '八宝粥', '烤鸡', '大雁', '音响', '招牌', '胡萝卜', '冰棍', '帽子', '菠萝', '蛋挞', '香水', '泥猴桃', '吐司', '溪流', '黄豆', '樱桃', '小鸽子', '小蝴蝶', '爆米花', '花卷', '小鸭子', '小海豚', '日记本', '小熊猫', '小懒猪', '小懒虫', '荔枝', '镜子', '曲奇', '金针菇', '小松鼠', '小虾米', '酒窝', '紫菜', '金鱼', '柚子', '果汁', '百褶裙', '项链', '帆布鞋', '火龙果', '奇异果', '煎蛋', '唇彩', '小土豆', '高跟鞋', '戒指', '雪糕', '睫毛', '铃铛', '手链', '香氛', '红酒', '月光', '酸奶', '银耳汤', '咖啡豆', '小蜜蜂', '小蚂蚁', '蜡烛', '棉花糖', '向日葵', '水蜜桃', '小蝴蝶', '小刺猬', '小丸子', '指甲油', '康乃馨', '糖豆', '薯片', '口红', '超短裙', '乌冬面', '冰淇淋', '棒棒糖', '长颈鹿', '豆芽', '发箍', '发卡', '发夹', '发带', '铃铛', '小馒头', '小笼包', '小甜瓜', '冬瓜', '香菇', '小兔子', '含羞草', '短靴', '睫毛膏', '小蘑菇', '跳跳糖', '小白菜', '草莓', '柠檬', '月饼', '百合', '纸鹤', '小天鹅', '云朵', '芒果', '面包', '海燕', '小猫咪', '龙猫', '唇膏', '鞋垫', '羊', '黑猫', '白猫', '万宝路', '金毛', '山水', '音响');

        $nicName = $randomXing[rand(0, count($randomXing) - 1)] . $randomMing[rand(0, count($randomMing) - 1)];

        return $nicName; // 返回生成的昵称
    }

    function getname($name_count = 1, $file_name = 'name.txt')
    {
        $lastname_arr = array('赵', '钱', '孙', '李', '周', '吴', '郑', '王', '冯', '陈', '褚', '卫', '蒋', '沈', '韩', '杨', '朱', '秦', '尤', '许', '何', '吕', '施', '张', '孔', '曹', '严', '华', '金', '魏', '陶', '姜',
            '戚', '谢', '邹', '喻', '柏', '水', '窦', '章', '云', '苏', '潘', '葛', '奚', '范', '彭', '郎', '鲁', '韦', '昌', '马', '苗', '凤', '花', '方', '任', '袁', '柳', '鲍', '史', '唐', '费', '薛', '雷', '贺', '倪',
            '汤', '滕', '殷', '罗', '毕', '郝', '安', '常', '傅', '卞', '齐', '元', '顾', '孟', '平', '黄', '穆', '萧', '尹', '姚', '邵', '湛', '汪', '祁', '毛', '狄', '米', '伏', '成', '戴', '谈', '宋', '茅', '庞', '熊',
            '纪', '舒', '屈', '项', '祝', '董', '梁', '杜', '阮', '蓝', '闵', '季', '贾', '路', '娄', '江', '童', '颜', '郭', '梅', '盛', '林', '钟', '徐', '邱', '骆', '高', '夏', '蔡', '田', '樊', '胡', '凌', '霍', '虞',
            '万', '支', '柯', '管', '卢', '莫', '柯', '房', '裘', '缪', '解', '应', '宗', '丁', '宣', '邓', '单', '杭', '洪', '包', '诸', '左', '石', '崔', '吉', '龚', '程', '嵇', '邢', '裴', '陆', '荣', '翁', '荀', '于',
            '惠', '甄', '曲', '封', '储', '仲', '伊', '宁', '仇', '甘', '武', '符', '刘', '景', '詹', '龙', '叶', '幸', '司', '黎', '溥', '印', '怀', '蒲', '邰', '从', '索', '赖', '卓', '屠', '池', '乔', '胥', '闻', '莘',
            '党', '翟', '谭', '贡', '劳', '逄', '姬', '申', '扶', '堵', '冉', '宰', '雍', '桑', '寿', '通', '燕', '浦', '尚', '农', '温', '别', '庄', '晏', '柴', '瞿', '阎', '连', '习', '容', '向', '古', '易', '廖', '庾',
            '终', '步', '都', '耿', '满', '弘', '匡', '国', '文', '寇', '广', '禄', '阙', '东', '欧', '利', '师', '巩', '聂', '关', '荆', '司马', '上官', '欧阳', '夏侯', '诸葛', '闻人', '东方', '赫连', '皇甫', '尉迟',
            '公羊', '澹台', '公冶', '宗政', '濮阳', '淳于', '单于', '太叔', '申屠', '公孙', '仲孙', '轩辕', '令狐', '徐离', '宇文', '长孙', '慕容', '司徒', '司空');
        $firstname_arr = array('伟', '刚', '勇', '毅', '俊', '峰', '强', '军', '平', '保', '东', '文', '辉', '力', '明', '永', '健', '世', '广', '志', '义', '兴', '良', '海', '山', '仁', '波', '宁', '贵', '福', '生', '龙',
            '元', '全', '国', '胜', '学', '祥', '才', '发', '武', '新', '利', '清', '飞', '彬', '富', '顺', '信', '子', '杰', '涛', '昌', '成', '康', '星', '光', '天', '达', '安', '岩', '中', '茂', '进', '林', '有', '坚',
            '和', '彪', '博', '诚', '先', '敬', '震', '振', '壮', '会', '思', '群', '豪', '心', '邦', '承', '乐', '绍', '功', '松', '善', '厚', '庆', '磊', '民', '友', '裕', '河', '哲', '江', '超', '浩', '亮', '政', '谦',
            '亨', '奇', '固', '之', '轮', '翰', '朗', '伯', '宏', '言', '若', '鸣', '朋', '斌', '梁', '栋', '维', '启', '克', '伦', '翔', '旭', '鹏', '泽', '晨', '辰', '士', '以', '建', '家', '致', '树', '炎', '德', '行',
            '时', '泰', '盛', '雄', '琛', '钧', '冠', '策', '腾', '楠', '榕', '风', '航', '弘', '秀', '娟', '英', '华', '慧', '巧', '美', '娜', '静', '淑', '惠', '珠', '翠', '雅', '芝', '玉', '萍', '红', '娥', '玲', '芬',
            '芳', '燕', '彩', '春', '菊', '兰', '凤', '洁', '梅', '琳', '素', '云', '莲', '真', '环', '雪', '荣', '爱', '妹', '霞', '香', '月', '莺', '媛', '艳', '瑞', '凡', '佳', '嘉', '琼', '勤', '珍', '贞', '莉', '桂',
            '娣', '叶', '璧', '璐', '娅', '琦', '晶', '妍', '茜', '秋', '珊', '莎', '锦', '黛', '青', '倩', '婷', '姣', '婉', '娴', '瑾', '颖', '露', '瑶', '怡', '婵', '雁', '蓓', '纨', '仪', '荷', '丹', '蓉', '眉', '君',
            '琴', '蕊', '薇', '菁', '梦', '岚', '苑', '婕', '馨', '瑗', '琰', '韵', '融', '园', '艺', '咏', '卿', '聪', '澜', '纯', '毓', '悦', '昭', '冰', '爽', '琬', '茗', '羽', '希', '欣', '飘', '育', '滢', '馥', '筠',
            '柔', '竹', '霭', '凝', '晓', '欢', '霄', '枫', '芸', '菲', '寒', '伊', '亚', '宜', '可', '姬', '舒', '影', '荔', '枝', '丽', '阳', '妮', '宝', '贝', '初', '程', '梵', '罡', '恒', '鸿', '桦', '骅', '剑', '娇',
            '纪', '宽', '苛', '灵', '玛', '媚', '琪', '晴', '容', '睿', '烁', '堂', '唯', '威', '韦', '雯', '苇', '萱', '阅', '彦', '宇', '雨', '洋', '忠', '宗', '曼', '紫', '逸', '贤', '蝶', '菡', '绿', '蓝', '儿', '翠',
            '钱', '孙', '李', '周', '吴', '郑', '王', '冯', '陈', '褚', '卫', '蒋', '沈', '韩', '杨', '朱', '秦', '尤', '许', '何', '吕', '施', '张', '孔', '曹', '严', '华', '金', '魏', '陶', '姜', '戚', '谢', '邹', '喻', '柏', '水', '窦', '章', '云', '苏', '潘', '葛', '奚', '范', '彭', '郎', '鲁', '韦', '昌', '马', '苗', '凤', '花', '方', '任', '袁', '柳', '鲍', '史', '唐', '费', '薛', '雷', '贺', '倪', '汤', '滕', '殷', '罗', '毕', '郝', '安', '常', '傅', '卞', '齐', '元', '顾', '孟', '平', '黄', '穆', '萧', '尹', '姚', '邵', '湛', '汪', '祁', '毛', '狄', '米', '伏', '成', '戴', '谈', '宋', '茅', '庞', '熊', '纪', '舒', '屈', '项', '祝', '董', '梁', '杜', '阮', '蓝', '闵', '季', '贾', '路', '娄', '江', '童', '颜', '郭', '梅', '盛', '林', '钟', '徐', '邱', '骆', '高', '夏', '蔡', '田', '樊', '胡', '凌', '霍', '虞', '万', '支', '柯', '管', '卢', '莫', '柯', '房', '裘', '缪', '解', '应', '宗', '丁', '宣', '邓', '单', '杭', '洪', '包', '诸', '左', '石', '崔', '吉', '龚', '程', '嵇', '邢', '裴', '陆', '荣', '翁', '荀', '于', '惠', '甄', '曲', '封', '储', '仲', '伊', '宁', '仇', '甘', '武', '符', '刘', '景', '詹', '龙', '叶', '幸', '司', '黎', '溥', '印', '怀', '蒲', '邰', '从', '索', '赖', '卓', '屠', '池', '乔', '胥', '闻', '莘', '党', '翟', '谭', '贡', '劳', '逄', '姬', '申', '扶', '堵', '冉', '宰', '雍', '桑', '寿', '通', '燕', '浦', '尚', '农', '温', '别', '庄', '晏', '柴', '瞿', '阎', '连', '习', '容', '向', '古', '易', '廖', '庾', '终', '步', '都', '耿', '满', '弘', '匡', '国', '文', '寇', '广', '禄', '阙', '东', '欧', '利', '师', '巩', '聂', '关', '荆',
            '烟');
        if (rand(1, 2) == 1) {
            $nicName = $lastname_arr[rand(0, count($lastname_arr) - 1)] . $firstname_arr[rand(0, count($firstname_arr) - 1)];
        } else {
            $nicName = $lastname_arr[rand(0, count($lastname_arr) - 1)] . $firstname_arr[rand(0, count($firstname_arr) - 1)] . $firstname_arr[rand(0, count($firstname_arr) - 1)];
        }
        return $nicName; // 返回生成的昵称
    }

    public function red()
    {
        $request = Request::instance();
        $uid = $request->param("uid");
        $token = $request->param("token") ?: 0;//
        $jm_str = $request->param("jm_str") ?: 0;//
        $user = Db::name("userhome")->where('id', $uid)->find();
        $redRole = Db::name("red_role")->find();
        if($redRole){
            if(!$redRole['status']){
                $this->error('红包兑换功能维护中');
            }
        }
        $redIdList = [];
        $red = Db::name("red")->order('sort', 'asc')->select();
        if (empty($user)) {
            foreach ($red as $key => $value) {
                $red[$key]['isUse'] = 1;
            }
        } else {
            if (isset($user['redId']) && !empty($user['redId'])) {
                $redIdList = explode(';', $user['redId']);
            }
            foreach ($red as $key => $value) {
                $red[$key]['isUse'] = 0;
                if (in_array($value['id'], $redIdList)) {
                    $red[$key]['isUse'] = 1;
                }
            }
        }
        $this->success('成功', $red, 200);
    }

    public function getRedPrice()
    {
        $request = Request::instance();
        $uid = $request->param("uid");
        $token = $request->param("token") ?: 0;//
        $jm_str = $request->param("jm_str") ?: 0;//
        $redId = $request->param("redId");//
        $res = yanzheng($uid, $token, $jm_str);
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        if (!isset($redId) || empty($redId)) {
            $this->error('红包id不对劲');
        }
        if (empty($uid)) {
            $this->error("请登录", '', '201');
        }
        try {
            Db::startTrans();
            $user = Db::name("userhome")->where('id', $uid)->lock()->find();
            if ((!isset($user['appletOpenid']) || empty($user['appletOpenid'])) && (!isset($user['appOpenid']) || empty($user['appOpenid'])) && (!isset($user['pcOpenid']) || empty($user['pcOpenid']))) {
                $this->error('未检测到用户微信小程序或app的绑定,请重新登录，或绑定后尝试');
            }
            $redRole = Db::name("red_role")->find();
            if($redRole){
                if(!$redRole['status']){
                    $this->error('红包兑换功能维护中');
                }
            }
            $red = Db::name("red")->where('id', $redId)->find();
            if (!$red) {
                $this->error('红包已被下架');
            }
            $redIdList = [];
            if (isset($user['redId']) && !empty($user['redId'])) {
                $redIdList = explode(';', $user['redId']);
            }
            $useNum = 0;
            foreach ($redIdList as $value){
                if($redId == $value){
                    $useNum++;
                }
            }
            if ($useNum >= $red['num']) {
                $this->error('红包已无兑换次数');
            }
            if (intval(strval($user['use_integral'] * 100)) < intval(strval($red['integral'] * 100))) {
                $this->error('可使用积分不足,无法购买', '', 209);
            }
            $redNo = date('Ymd') . '3' . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . rand(0, 9);//生成支付单号
            //发送红包
            $break = $red['redName'];
            $openid = null;
            $appId = null;
            if (isset($user['appletOpenid']) && !empty($user['appletOpenid'])) {
                $openid = $user['appletOpenid'];
                $appId = "wx4a40935421da4a92";
            } else {
                if (isset($user['appOpenid']) && !empty($user['appOpenid'])) {
                    $openid = $user['appOpenid'];
                    $appId = "wx09c4b8eabf581e35";
                } else {
                    if (isset($user['pcOpenid']) && !empty($user['pcOpenid'])) {
                        $openid = $user['pcOpenid'];
                        $appId = "wx175ea5edf592c9e5";
                    }
                }
            }
            include './WeixinPay.php';
            $wx = new \WeixinPay();//实例化微信支付控制器
            $res = $wx->sendRedPrice($openid, $break, $appId, $redNo, $red['price'] * 100);
            $status = "ENTER";
            $break = "使用了积分兑换了" . $red['redName'];
            if ($res['return_code'] != "SUCCESS" || $res['result_code'] != "SUCCESS") {
                $status = "PAST";
                $break = $res['err_code_des'];
                $this->error($break, "", "309");
            } else {
                DB::name('userhome')->where(['id' => $uid])->setDec("use_integral", $red['integral']);
                $redIdList[] = $red['id'];
                $redIdList = implode(';', $redIdList);
                DB::name('userhome')->where(['id' => $uid])->update(["redId" => $redIdList]);
            }
            $incomeScoreLog = [
                'userId' => $uid,
                'score' => $red['integral'],
                'grandScore' => $user['add_integral'],
                'consumeScore' => (intval(strval($user['use_integral'] * 100)) - intval(strval($red['integral'] * 100))) / 100,
                'source' => "RED",
                'createTime' => date("Y-m-d H:i:s"),//下单时间
                'status' => $status,
                'break' => $break,
                'red_id' => $red['id'],
                'redType' => "WX",
                'redNum' => $red['price'],
                'redName' => $red['redName'],
                'redNo' => $redNo
            ];
            DB::name('user_income_score_log')->insert($incomeScoreLog);
            $incomeScoreLog = [
                'red_id' => $red['id'],
                'userId' => $uid,
                'redType' => "WX",
                'createTime' => date("Y-m-d H:i:s"),//下单时间
                'redNum' => $red['price'],
                'score' => $red['integral'],
                'redNo' => $redNo,
                'redName' => $red['redName'],
                'status' => $status,
                'break' => $break,
            ];
            DB::name('user_integral_red_log')->insert($incomeScoreLog);
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('红包兑换成功,将在两小时内到账,请注意查收', true, 200);
    }


    public function redLog()
    {
        $request = Request::instance();
        $uid = $request->param("uid");
        $token = $request->param("token") ?: 0;//
        $jm_str = $request->param("jm_str") ?: 0;//
        $pagesize = $request->param("pagesize") ?: 10;//
        $res = yanzheng($uid, $token, $jm_str);
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        if (empty($uid)) {
            $this->error("请登录", '', '201');
        }
        $redLogList = Db::name("user_integral_red_log")->where('userId',$uid)->order('createTime', 'DESC')->paginate($pagesize);
        $data = [];
        $data['redLogList'] = $redLogList->items();
        $data['totalNum'] = $redLogList->total();
        $this->success('成功', $data, 200);
    }
}